import axios from 'axios'
import ElementUI from 'element-ui'
import router from './router'
import store from './store'
import 'element-ui/lib/theme-chalk/index.css'

axios.defaults.baseURL = 'http://localhost:8080'

// 前置拦截
axios.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (localStorage.getItem('token') !== undefined && localStorage.getItem('token')) {
      config.headers.Authorization = localStorage.getItem('token')
    }
    return config
  },
  error => {
    // Do something with request error
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    // Do something before response is sent
    let res = response.data
    console.log('============')
    console.log(res)
    console.log('============')

    if (res.code === 200) {
      return response
    } else {
      ElementUI.Message.error({
        title: '错误',
        message: res.msg,
        duration: 2.5 * 1000
      })
      return Promise.reject(response.data.message)
    }
  },
  error => {
    // Do something with response error
    if (error.response.data !== '') {
      error.msg = error.response.data.msg
    }
    if (error.response.status === 401) {
      store.commit('REMOVE_INFO')
      router.push('/').then(r => {
        this.$store.getters.getUser = null
      })
      router.go(0)
    }

    ElementUI.Message.error({
      title: '错误',
      message: error.msg,
      duration: 2.5 * 1000
    })
    return Promise.reject(error)
  }
)
